package com.kalaqia.base.ui.list;

import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * @author kalaqia 421407393@qq.com
 */
@SuppressWarnings({"unused", "WeakerAccess"})
public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

    private int top, right, bottom, left;
    private boolean isEdge;

    public SpaceItemDecoration(int dimen) {
        this(dimen, false);
    }

    public SpaceItemDecoration(int dimen, boolean isEdge) {
        this(dimen, dimen, isEdge);
    }

    @SuppressWarnings("WeakerAccess")
    public SpaceItemDecoration(int horizontalDimen, int verticalDimen, boolean isEdge) {
        this(horizontalDimen, verticalDimen, horizontalDimen, verticalDimen, isEdge);
    }

    public SpaceItemDecoration(int left, int top, int right, int bottom, boolean isEdge) {
        this.top = top;
        this.right = right;
        this.bottom = bottom;
        this.left = left;
        this.isEdge = isEdge;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent
            , @NonNull RecyclerView.State state) {

        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();

        if (layoutManager instanceof LinearLayoutManager) {
            doInLinearLayout((LinearLayoutManager) layoutManager, outRect, view, parent);
        }

    }

    private void doInLinearLayout(@NonNull LinearLayoutManager layoutManager, @NonNull Rect outRect
            , @NonNull View view, @NonNull RecyclerView parent) {
        if (!isEdge) {
            outRect.left = left;
            outRect.right = right;
            outRect.top = top;
            outRect.bottom = bottom;
            return;
        }

        boolean isFirst = parent.getChildAdapterPosition(view) == 0;
        outRect.top = isFirst ? top : 0;
        outRect.left = left;
        outRect.right = right;
        outRect.bottom = bottom;

    }
}
